package org.zj.springstyle.mvc.controller;

import org.zj.springstyle.mvc.domain.IController;
import org.zj.springstyle.mvc.domain.NavigationMap;
import org.zj.springstyle.mvc.domain.SuperDomain;
import org.zj.springstyle.mvc.parseJSON.NativatorBean;
import org.zj.springstyle.mvc.parseXml.XMLBeans;
import org.zj.springstyle.mvc.util.Reflect4domain;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by zhaoji on 14/12/23.
 */
public class DispatchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String path = this.getRequestPath(req.getServletPath());
        XMLBeans xmlBeans = null;
        NativatorBean nb = null;
        String formclass = "";
        String actionClass = "";
        String url = "";
        System.out.println(path);
        Map<String,NativatorBean> jsonMap = (Map<String,NativatorBean> ) this.getServletContext().getAttribute("json");
        Map<String,XMLBeans> xmlMap = (Map<String,XMLBeans> ) this.getServletContext().getAttribute("struts");
        if(jsonMap!=null){
            nb = jsonMap.get(path);
            formclass = nb.getFormBeanClass();
            actionClass = nb.getControllerClass();
            SuperDomain superDomain = Reflect4domain.gainClass(formclass,req);
            IController I = null;
            try {
                Class clazz = Class.forName(actionClass);
                I = (IController)clazz.newInstance();
                url = I.execute(req,resp,superDomain,nb.getMap());
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            xmlBeans = xmlMap.get(path);
            formclass = xmlBeans.getFormClass();
            actionClass = xmlBeans.getActionClass();
            SuperDomain superDomain = Reflect4domain.gainClass(formclass,req);
            IController I = null;
            try {
                Class clazz = Class.forName(actionClass);
                I = (IController)clazz.newInstance();
                url = I.execute(req,resp,superDomain,xmlBeans.getMap());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        RequestDispatcher dispatcher = req.getRequestDispatcher(url);
        dispatcher.forward(req,resp);
    }

    private String getRequestPath(String servletPath){
        return servletPath.split("\\.")[0];
    }


}
